import { useState, useRef, useEffect, useCallback } from "react";
import PropTypes from "prop-types";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { faSearch, faTimes } from "@fortawesome/free-solid-svg-icons";
import useKeyPress from "@/hooks/useKeyPress";
import sty from "./index.module.scss";

export default function FileSearch({ title, onFileSearch }) {
  const [showSearch, setShowSearch] = useState(false);
  const [fileName, setFileName] = useState("");
  const inputRef = useRef(null);
  const enterPress = useKeyPress(13);
  const escPress = useKeyPress(27);

  const closeSearch = useCallback(() => {
    setShowSearch(false);
    setFileName("");
    onFileSearch("");
  }, [onFileSearch]);

  useEffect(() => {
    if (enterPress && showSearch) {
      onFileSearch(fileName);
    } else if (escPress && showSearch) {
      closeSearch();
    }
  }, [escPress, enterPress, showSearch, onFileSearch, closeSearch, fileName]);

  useEffect(() => {
    if (showSearch && inputRef.current) {
      inputRef.current.focus();
    }
  }, [showSearch]);

  return (
    <>
      {showSearch ? (
        <div
          className={`p-3 d-flex  justify-content-between align-items-center ${sty.fileSearch}`}
        >
          <input
            type="text"
            className="form-control"
            value={fileName}
            ref={inputRef}
            onChange={(e) => setFileName(e.target.value)}
          />
          <button type="button" className="icon-btn" onClick={closeSearch}>
            <FontAwesomeIcon icon={faTimes} title="取消" />
          </button>
        </div>
      ) : (
        <div className="p-3 d-flex  justify-content-between align-items-center file-search">
          <div>{title}</div>
          <button
            type="button"
            className="icon-btn"
            onClick={() => setShowSearch(true)}
          >
            <FontAwesomeIcon icon={faSearch} title="搜索" />
          </button>
        </div>
      )}
    </>
  );
}

FileSearch.propTypes = {
  onFileSearch: PropTypes.func.isRequired,
  title: PropTypes.string,
};

FileSearch.defaultProps = {
  title: "我的文档",
};
